# -*- coding: utf-8 -*-
from __future__ import print_function

from datetime import datetime, timedelta
from ddl_platform.database.silence_job_table import silence_job_table
from ddl_platform.database.profiled_job_table import profiled_job_table
from ddl_platform.database.scheduling_job_table import scheduling_job_table
from ddl_platform.ddlib.job import JobStatus


def statistic_jobs():
    submitted_jobs = silence_job_table.query()
    jobs = profiled_job_table.query()
    jobs.sort(key=lambda x: x._completion_time)
    latest_finish_time = datetime.fromtimestamp(jobs[-1]._completion_time)

    jobs.sort(key=lambda x: x._arrival_time)
    earliest_arrival_time = datetime.fromtimestamp(jobs[0]._arrival_time)
    averate_completion_time = 0.0
    available_job_counter = 0
    exception_jobs = []
    num_migration_jobs = 0
    #print('jobs: ', jobs)
    for job in jobs:
        arrival_time = datetime.fromtimestamp(job._arrival_time)
        completion_time = datetime.fromtimestamp(job._completion_time)
        if job.get_status() == JobStatus.EXCEPTION:
            exception_jobs.append(job)
        elif job.get_status() == JobStatus.MIGRATION:
            num_migration_jobs += 1
        if job._completion_time == -1:
            continue
        available_job_counter += 1
        interval = (completion_time - arrival_time).total_seconds()
        averate_completion_time += interval
        print('job: ', job, arrival_time, completion_time, str(interval) + ' sec')
    print('======== Job statistic ===========')
    print('- # of submitted jobs: ', len(submitted_jobs))
    print('- # of profilied jobs: ', len(jobs))
    print('- # of migration jobs: ', num_migration_jobs)
    print('- # of completed jobs: ', available_job_counter)
    print('- # of exception jobs: ', len(exception_jobs))
    for ej in exception_jobs:
        print('-- ', ej.get_id(), ej._exception)

    print('- Earliest arrival time: ', earliest_arrival_time)
    print('- Latest finish time: ', latest_finish_time)
    print('- Makespan: ', latest_finish_time-earliest_arrival_time, ' seconds')
    print('- Average completion time: ', averate_completion_time/available_job_counter, ' seconds')


if __name__ == '__main__':
    statistic_jobs()
